import { isFunction } from "../shared/index";

export function createComponentInstance(vnode) {
  const instance = {
    type: vnode.type,
    props: {},
    vnode,
    isMounted: false
  }
  return instance
}

export let currentInstance = null;
export let setCurrentInstance = (instance) =>{
    currentInstance = instance;
}
export let getCurrentInstance = () =>{ // 在setuop中获取当前实例 
    return currentInstance
}




export const setupComponent = (instance) => {
  // 
  setupStatefulComponent(instance)
}


function setupStatefulComponent(instance) {
  
  const Component = instance.type;
  const {setup} = Component;
  if(setup) {
    currentInstance = instance;
    const setUpResult = setup();
    currentInstance = null;
    // 判断返回值类型
    handleSetupResult(instance,setUpResult);
  }
}

function handleSetupResult(instance,setUpResult) {
  if(isFunction(setUpResult)) {
    instance.render = setUpResult
  }else {
    instance.setupState = setUpResult
  }
  finishComponentSetup(instance)
}


function finishComponentSetup(instance) {
  const Component = instance.type;
  if (Component.render) {
    instance.render = Component.render; // 默认的优先级高于setup
  }
}